package gen

import (
	"fmt"
	"os"
	"regexp"
	"strings"

	"gitee.com/krio/ginc/util"
	"github.com/gookit/color"
)

const (
	swaggerFileName = "apidocs.swagger.json" // swagger文件名称（这是openapiv2_out处理的，修改没有啥用）
)

// FormatDocFile 编辑 api/swagger.json的info.description
func (g *Generator) FormatDocFile() error {
	color.Bluep("[ 文档分组 ]", "\n")
	swaggerFilePath := g.ToDocPath + "/" + swaggerFileName
	if !util.FileExists(swaggerFilePath) {
		return nil
	}
	bt, err := os.ReadFile(swaggerFilePath)
	if err != nil {
		return err
	}
	body := string(bt)
	serviceNodeMap := make(map[string]string, len(g.protoList))
	var maxNameLen int
	for _, v := range g.protoList {
		serviceNodeMap[v.Service.Name] = v.Option.ServiceNodeName
		length := len(v.Service.Name)
		if length > maxNameLen {
			maxNameLen = length
		}
	}
	for svcName, nodeName := range serviceNodeMap {
		complexStr := fmt.Sprintf(`"%s"`, svcName)
		if strings.Contains(body, complexStr) {
			reg := regexp.MustCompile(complexStr)
			fs := reg.FindString(body)
			body = strings.ReplaceAll(body, fs, "\""+nodeName+"\"")
		}
		util.EqualLengthPrint(svcName, nodeName, maxNameLen)
	}
	if err = os.WriteFile(swaggerFilePath, []byte(body), 0644); err != nil {
		return err
	}
	return nil
}
